package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dto.LogisticsPriceDTO;
import com.itheima.mapper.LogisticsCompanyMapper;
import com.itheima.mapper.LogisticsPriceMapper;
import com.itheima.pojo.LogisticsCompany;
import com.itheima.pojo.LogisticsPrice;
import com.itheima.service.LogisticsPriceService;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class LogisticsPriceServiceImpl extends ServiceImpl<LogisticsPriceMapper, LogisticsPrice> implements LogisticsPriceService {
    @Autowired
    private LogisticsPriceMapper logisticsPriceMapper;

    @Autowired
    private LogisticsCompanyMapper logisticsCompanyMapper;

    @Override
    public Page<LogisticsPriceDTO> getLogisticsPricePage(Page<LogisticsPriceDTO> page, LogisticsPriceDTO dto) {
        PageHelper.startPage((int) page.getCurrent(), (int) page.getSize());

        LambdaQueryWrapper<LogisticsPrice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LogisticsPrice::getIsDel, 1);

        if (dto != null) {
            if (dto.getCategory() != null) {
                wrapper.eq(LogisticsPrice::getCategory, dto.getCategory());
            }
            if (dto.getLogisticsCompanyId() != null) {
                wrapper.eq(LogisticsPrice::getLogisticsCompanyId, dto.getLogisticsCompanyId());
            }
            if (StringUtils.isNotBlank(dto.getSaasId())) {
                wrapper.eq(LogisticsPrice::getSaasId, dto.getSaasId());
            }
        }

        List<LogisticsPrice> list = this.list(wrapper);
        PageInfo<LogisticsPrice> pageInfo = new PageInfo<>(list);

        Page<LogisticsPriceDTO> dtoPage = new Page<>(page.getCurrent(), page.getSize(), pageInfo.getTotal());
        dtoPage.setRecords(convertToDtoList(list));
        return dtoPage;
    }

    @Override
    public LogisticsPrice getLogisticsPriceById(Long id) {
        LambdaQueryWrapper<LogisticsPrice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LogisticsPrice::getId, id)
                .eq(LogisticsPrice::getIsDel, 1);
        return this.getOne(wrapper);
    }

    @Override
    public boolean saveLogisticsPrice(LogisticsPrice logisticsPrice) {
        if (logisticsPrice.getId() == null) {
            logisticsPrice.setCreateTime(LocalDateTime.now());
            logisticsPrice.setIsDel(1);
            return this.save(logisticsPrice);
        } else {
            logisticsPrice.setUpdateTime(LocalDateTime.now());
            return this.updateById(logisticsPrice);
        }
    }

    @Override
    public boolean updateLogisticsPrice(LogisticsPrice logisticsPrice) {
        logisticsPrice.setUpdateTime(LocalDateTime.now());
        return this.updateById(logisticsPrice);
    }

    @Override
    public boolean deleteLogisticsPrice(Long id) {
        LogisticsPrice logisticsPrice = new LogisticsPrice();
        logisticsPrice.setId(id);
        logisticsPrice.setIsDel(2);
        logisticsPrice.setUpdateTime(LocalDateTime.now());
        return this.updateById(logisticsPrice);
    }

    @Override
    public List<LogisticsPrice> listAll() {
        LambdaQueryWrapper<LogisticsPrice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LogisticsPrice::getIsDel, 1);
        return this.list(wrapper);
    }

    @Override
    public List<LogisticsPriceDTO> queryPricesByCompany(Integer companyId) {
        // 构建查询条件
        LambdaQueryWrapper<LogisticsPrice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LogisticsPrice::getLogisticsCompanyId, companyId)
                .eq(LogisticsPrice::getIsDel, 1); // 只查询未删除的

        // 执行查询
        List<LogisticsPrice> prices = logisticsPriceMapper.selectList(wrapper);

        // 转换为DTO
        return prices.stream().map(this::convertToDto).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSavePrices(Integer companyId, List<LogisticsPriceDTO> priceDTOs) {
        // 1. 验证物流公司是否存在
        LogisticsCompany company = logisticsCompanyMapper.selectById(companyId);
        if (company == null || company.getIsDel() != 1) {
            throw new RuntimeException("物流公司不存在或已删除");
        }

        // 2. 转换DTO为Entity
        List<LogisticsPrice> prices = priceDTOs.stream()
                .map(dto -> {
                    LogisticsPrice entity = new LogisticsPrice();
                    BeanUtils.copyProperties(dto, entity);
                    entity.setLogisticsCompanyId(companyId);
                    entity.setCreateTime(LocalDateTime.now());
                    entity.setIsDel(1);
                    return entity;
                })
                .collect(Collectors.toList());

        // 3. 批量保存
        return logisticsPriceMapper.batchInsert(prices) == priceDTOs.size();
    }

    private LogisticsPriceDTO convertToDto(LogisticsPrice logisticsPrice) {
        LogisticsPriceDTO dto = new LogisticsPriceDTO();
        BeanUtils.copyProperties(logisticsPrice, dto);
        dto.setIsValid(logisticsPrice.getIsDel());
        return dto;
    }

    private List<LogisticsPriceDTO> convertToDtoList(List<LogisticsPrice> list) {
        return list.stream().map(this::convertToDto).collect(Collectors.toList());
    }
}